package com.crack.nga2.custom;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Vibrator;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;

/**
 * 可拖拽的GridView
 * Created by Administrator on 2016/1/20.
 */
public class DragGridView extends GridView {
    /**
     * 长按响应时间
     */
    private long dragResponseMs = 1000;

    private int mDownX;
    private int mDownY;
    private int moveX;
    private int moveY;
    /**
     * 拖拽的view的position
     */
    private int mDragPosition;
    /**
     * 拖拽的view
     */
    private View mStartDragItemView;
    /**
     * 拖拽镜像
     */
    private ImageView mDragImageView;
    /**
     * 振动器
     */
    private Vibrator mVibrator;
    private WindowManager mWindowManager;
    private WindowManager.LayoutParams mWindowLayoutParams;
    /**
     * 拖拽的bitmap
     */
    private Bitmap mDragBitmap;
    /**
     * 按下的点到item上边缘的距离
     */
    private int mPoint2ItemTop;
    /**
     * 按下的点到item左边缘的距离
     */
    private int mPoint2ItemLeft;
    /**
     * DragGridView距离屏幕顶部的偏移量
     */
    private int mOffset2Left = 0;
    /**
     * DragGridView距离屏幕左边的偏移量
     */
    private int mOffset2Top = 0;
    /**
     * 状态栏高度
     */
    private int mStatusHeight;
    /**
     * 点击这些position的item无效
     */
    private int[] noDragPositions;

    public DragGridView(Context context) {
        super(context);
        init();
    }

    public DragGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public DragGridView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private Handler mHandler = new Handler();

    private void init() {
        mVibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
        mWindowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        mStatusHeight = getStatusHeight(getContext());
    }

    private int getStatusHeight(Context context) {
        int statusHeight;
        Rect localRect = new Rect();
        ((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(localRect);
        statusHeight = localRect.top;
        if (0 == statusHeight) {
            Class<?> localClass;
            try {
                localClass = Class.forName("com.android.internal.R$dimen");
                Object localObject = localClass.newInstance();
                int i5 = Integer.parseInt(localClass.getField("status_bar_height").get(localObject).toString());
                statusHeight = context.getResources().getDimensionPixelSize(i5);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return statusHeight;
    }

    private boolean isDrag;

    private Runnable mLongClickRunnable = new Runnable() {
        @Override
        public void run() {
            //防止一个小BUG
            if (isDrag) {
                isDrag = false;
                mWindowManager.removeView(mDragImageView);
            }
            isDrag = true;
            mVibrator.vibrate(50);
            Log.i("drag", "开始初始化");
            //创建item镜像
            createDragImage(mDragBitmap, mDownX, mDownY);
        }
    };

    private CompleteDragListener mCompleteDragListener;

    public void setOnCompleteDragListener(CompleteDragListener listener) {
        mCompleteDragListener = listener;
    }


    public interface CompleteDragListener {
        void complete(int x, int y, int position);
    }

    /**
     * 创建拖拽镜像
     */
    private void createDragImage(Bitmap bitmap, int downX, int downY) {
        getLocationOnScreen(locationXY);
        mWindowLayoutParams = new WindowManager.LayoutParams();
        mWindowLayoutParams.format = PixelFormat.TRANSPARENT;
        mWindowLayoutParams.gravity = Gravity.TOP | Gravity.START;
        mWindowLayoutParams.x = downX - mPoint2ItemLeft + mOffset2Left + locationXY[0];
        mWindowLayoutParams.y = downY - mPoint2ItemTop + mOffset2Top - mStatusHeight + locationXY[1];
        //透明度
        mWindowLayoutParams.alpha = 0.55f;
        mWindowLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        mWindowLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        mWindowLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;

        mDragImageView = new ImageView(getContext());
        mDragImageView.setImageBitmap(bitmap);

        mWindowManager.addView(mDragImageView, mWindowLayoutParams);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mDownX = (int) ev.getX();
                mDownY = (int) ev.getY();
                //获取点击的position
                mDragPosition = pointToPosition(mDownX, mDownY);

                if (noDragPositions != null) {
                    for (int position : noDragPositions) {
                        if (position == mDragPosition) {
                            break;
                        }
                    }
                }
                if (mDragPosition == AdapterView.INVALID_POSITION) {
                    break;
                }
                if (mDragPosition > getChildCount() - 1) {
                    break;
                }
                mHandler.removeCallbacks(mLongClickRunnable);
                mHandler.postDelayed(mLongClickRunnable, dragResponseMs);
                //根据获取的position获取点击的item的view
                mStartDragItemView = getChildAt(mDragPosition - getFirstVisiblePosition());
                mPoint2ItemTop = mDownY - mStartDragItemView.getTop();
                mPoint2ItemLeft = mDownX - mStartDragItemView.getLeft();

                //开启mDragItemView的绘图缓存
                mStartDragItemView.setDrawingCacheEnabled(true);
                Bitmap bitmap = mStartDragItemView.getDrawingCache();
                if (bitmap == null) {
                    View v = mStartDragItemView;
                    bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
                    Canvas c = new Canvas(bitmap);
                    v.draw(c);
                }
                mDragBitmap = Bitmap.createBitmap(bitmap);
                mStartDragItemView.destroyDrawingCache();
                break;
            case MotionEvent.ACTION_MOVE:
                //// TODO: 2016/1/20
                int x = (int) ev.getX();
                int y = (int) ev.getY();
                int p = pointToPosition(x, y);
                if (p != mDragPosition) {
                    mHandler.removeCallbacks(mLongClickRunnable);
                }
                break;
            case MotionEvent.ACTION_UP:
                Log.i("tag","action_up");
                mHandler.removeCallbacks(mLongClickRunnable);
                if (isDrag) {
                    onStopDrag();
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 是否点击在GridView的item上
     */
    private boolean isTouchInItem(View dragView, int x, int y) {
        int leftOffset = dragView.getLeft();
        int topOffset = dragView.getTop();
        if (x < leftOffset || x > leftOffset + dragView.getWidth()) {
            return false;
        }
        if (y < topOffset || y > topOffset + dragView.getHeight()) {
            return false;
        }
        return true;
    }

    private int[] locationXY = new int[2];

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (!isDrag || mDragImageView == null) {
            return super.onTouchEvent(ev);
        }
        switch (ev.getAction()) {
            case MotionEvent.ACTION_MOVE:
                getLocationOnScreen(locationXY);
                moveX = (int) ev.getX() - mPoint2ItemLeft + mOffset2Left + locationXY[0];
                moveY = (int) ev.getY() - mPoint2ItemTop + mOffset2Top - mStatusHeight + locationXY[1];
                onDragItem(moveX, moveY);
                break;
            case MotionEvent.ACTION_UP:
                if (isDrag) {
                    onStopDrag();
                }
                break;
        }
        return super.onTouchEvent(ev);
    }

    private void onStopDrag() {
        if (mCompleteDragListener != null) {
            mCompleteDragListener.complete(moveX, moveY, mDragPosition);
        }
        Log.i("drag", "停止拖动");
        isDrag = false;
        removeDragImage();
    }

    /**
     * 从界面上面移除拖动镜像
     */
    private void removeDragImage() {
        if (mDragImageView != null) {
            mWindowManager.removeView(mDragImageView);
            mDragImageView = null;
        }
    }

    public interface DragToXY {
        void dragToXY(int x, int y, int position);
    }

    private DragToXY dragToXY;

    public void setOnDragToXY(DragToXY dragToXY) {
        this.dragToXY = dragToXY;
    }

    /**
     * 拖动item
     */
    private void onDragItem(int moveX, int moveY) {
        mWindowLayoutParams.x = moveX;
        mWindowLayoutParams.y = moveY;
        mWindowManager.updateViewLayout(mDragImageView, mWindowLayoutParams); //更新镜像的位置
        if (dragToXY != null) {
            dragToXY.dragToXY(moveX, moveY, mDragPosition);
        }
    }

    public int[] getNoDragPositions() {
        return noDragPositions;
    }

    public void setNoDragPositions(int[] noDragPositions) {
        this.noDragPositions = noDragPositions;
    }

    public long getDragResponseMs() {
        return dragResponseMs;
    }

    public void setDragResponseMs(long dragResponseMs) {
        this.dragResponseMs = dragResponseMs;
    }
}
